//
//  TKYSafetyController.m
//  StationHouseHelper
//
//  Created by apple on 2018/5/7.
//  Copyright © 2018年 铁科院. All rights reserved.
//

#import "TKYSafetyController.h"
#import "TKYTitleButton.h"
#import "TKYDateView.h"
#import "BRPickerView.h"
#import "PTHistogramView.h"
#import "TKYCustomCharts.h"
#import "TKYProjectInfoModel.h"

@interface TKYSafetyController ()<UIScrollViewDelegate,TKYCustomChartsDelegate>
/**质量的问题类别(柱状图数据)*/
@property (nonatomic, strong)NSArray <TKYQuestionTypeListModel *>*questionTypeListArr;
@property (nonatomic, strong)TKYDateView *dateView;

/** 当前选中的标题按钮 */
@property (nonatomic, weak) TKYTitleButton *selectedTitleButton;
/** 标题按钮底部的指示器 */
@property (nonatomic, weak) UIView *indicatorView;
/** UIScrollView */
@property (nonatomic, weak) UIScrollView *scrollView;
/** 标题栏 */
@property (nonatomic, weak) UIView *titlesView;

@property (nonatomic, strong)UIView *mainView;

/**
 柱状图
 */
@property (nonatomic, strong) PTHistogramView *ptView;

/**
 自定义柱状图
 */
@property (nonatomic, strong)TKYCustomCharts *customCharts;

@end

@implementation TKYSafetyController

- (void)viewDidLoad {
    [super viewDidLoad];
     self.navigationItem.title = @"安全";
    
    self.mainView = [[UIView alloc]initWithFrame:CGRectMake(0, kHeightScale *200 +MyNavBarHeight, kScreenWidth, kScreenHeight-kHeightScale *200)];
    //self.mainView.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.mainView];
        
    [self setupChildViewControllers];
    
    [self setupScrollView];
    
    [self setupTitlesView];
    
    // 默认添加子控制器的view
    [self addChildVcView];
    
    [self.view addSubview:self.dateView];
    
   // [self.view addSubview:self.ptView];
    
    //请求数据(通过站房Id和质安标志获取问题类型及数量)
    self.projectInfoModel = [TKYProjectInfoModel sharedProjectInfoModel];
    [self requestQualityQuestionTypeAndCount:self.projectInfoModel.startDateStr withEndDateStr:self.projectInfoModel.endDateStr];
    
    [self.view addSubview:self.customCharts];

}

#pragma mark--- 请求数据(通过站房Id和质安标志获取问题类型及数量)
- (void)requestQualityQuestionTypeAndCount:(NSString *)sartDateStr withEndDateStr:(NSString *)endDateStr{
    NSString *url = [NSString stringWithFormat:@"%@%@projectId=%@&safeQualityFlag=2&startDateStr=%@&endDateStr=%@&token=%@",kApiBaseUrl,KGetQuestionTypeByProjectIdAndSafeQualityFlagUrl,[[NSUserDefaults standardUserDefaults]objectForKey:KStationHouseID],sartDateStr,endDateStr,[[NSUserDefaults standardUserDefaults]objectForKey:kToken]];
    [KHttpRequestTool GET:url parameters:nil success:^(id response) {
        if ([response[@"code"] integerValue] == 0) {
            self.questionTypeListArr = [TKYQuestionTypeListModel  mj_objectArrayWithKeyValuesArray:response[@"questionTypeList"]];
            _customCharts = [[TKYCustomCharts alloc]initWithFrame:CGRectMake(kWidthScale *10, self.dateView.kx_bottom, kScreenWidth - kWidthScale *20, kHeightScale *200 -_dateView.kx_height) withCustomChartsNSArray:self.questionTypeListArr];
            _customCharts.delegate = self;
            [self.view addSubview:self.customCharts];
                        [self.customCharts.collectionView reloadData];
            [SVProgressHUD dismiss];
        }else{
            [SVProgressHUD showErrorWithStatus:response[@"msg"]];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        
    }];
}

- (void)setupChildViewControllers
{
    self.allSafetyVC = [[TKYAllSafetyMessageController alloc] init];
    [self addChildViewController:self.allSafetyVC];
    
    self.safetyConductVC = [[TKYSafetyConductController alloc] init];
    // self.safetyConductVC.str = self.customChartArrM[0];
    [self addChildViewController:self.safetyConductVC];
    
    self.safetyFinishVC = [[TKYSafetyFinishController alloc] init];
    [self addChildViewController:self.safetyFinishVC];
}

- (void)setupScrollView
{
    // 不允许自动调整scrollView的内边距
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 35, kScreenWidth,0)];
    //scrollView.backgroundColor = [UIColor redColor];
    scrollView.frame = self.view.bounds;
    scrollView.pagingEnabled = YES;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.delegate = self;
    // 添加所有子控制器的view到scrollView中
    scrollView.contentSize = CGSizeMake(self.childViewControllers.count * scrollView.kx_width, 0);
    [self.mainView addSubview:scrollView];
    self.scrollView = scrollView;
}

- (void)setupTitlesView
{
    // 标题栏
    UIView *titlesView = [[UIView alloc] init];
    titlesView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.7];
    titlesView.frame = CGRectMake(0, 0, kScreenWidth, kHeightScale *35);
    [self.mainView addSubview:titlesView];
    
    self.titlesView = titlesView;
    
    // 添加标题
    NSArray *titles = @[@"全部", @"进行中", @"已完成"];
    NSUInteger count = titles.count;
    CGFloat titleButtonW = titlesView.kx_width / count;
    CGFloat titleButtonH = titlesView.kx_height;
    for (NSUInteger i = 0; i < count; i++) {
        // 创建
        TKYTitleButton *titleButton = [TKYTitleButton buttonWithType:UIButtonTypeCustom];
        titleButton.tag = i;
        [titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
        [titlesView addSubview:titleButton];
        
        // 设置数据
        [titleButton setTitle:titles[i] forState:UIControlStateNormal];
        
        // 设置frame
        titleButton.frame = CGRectMake(i * titleButtonW, 0, titleButtonW, titleButtonH);
    }
    
    // 按钮的选中颜色
    TKYTitleButton *firstTitleButton = titlesView.subviews.firstObject;
    
    UILabel *line = [[UILabel alloc]initWithFrame:CGRectMake(0, titlesView.kx_height - 1, kScreenWidth, 1)];
    line.backgroundColor = kMainColour;
    [self.titlesView addSubview:line];
    
    // 底部的指示器
    UIView *indicatorView = [[UIView alloc] init];
    indicatorView.backgroundColor = [firstTitleButton titleColorForState:UIControlStateSelected];
    indicatorView.kx_height = 1;
    indicatorView.kx_y = titlesView.kx_height - indicatorView.kx_height;
    [titlesView addSubview:indicatorView];
    self.indicatorView = indicatorView;
    
    
    
    // 立刻根据文字内容计算label的宽度
    [firstTitleButton.titleLabel sizeToFit];
    indicatorView.kx_width = firstTitleButton.titleLabel.kx_width;
    indicatorView.kx_centerX = firstTitleButton.kx_centerX;
    
    // 默认情况 : 选中最前面的标题按钮
    firstTitleButton.selected = YES;
    self.selectedTitleButton = firstTitleButton;
}

#pragma mark - 监听点击
- (void)titleClick:(TKYTitleButton *)titleButton
{
    // 某个标题按钮被重复点击
    if (titleButton == self.selectedTitleButton) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TKYTitleButtonDidRepeatClickNotification" object:nil];
    }
    
    // 控制按钮状态
    self.selectedTitleButton.selected = NO;
    titleButton.selected = YES;
    self.selectedTitleButton = titleButton;
    
    // 指示器
    [UIView animateWithDuration:0.25 animations:^{
        self.indicatorView.kx_width = titleButton.titleLabel.kx_width;
        self.indicatorView.kx_centerX = titleButton.kx_centerX;
    }];
    
    // 让UIScrollView滚动到对应位置
    CGPoint offset = self.scrollView.contentOffset;
    offset.x = titleButton.tag * self.scrollView.kx_width;
    [self.scrollView setContentOffset:offset animated:YES];
}

#pragma mark - 添加子控制器的view
- (void)addChildVcView
{
    // 子控制器的索引
    NSUInteger index = self.scrollView.contentOffset.x / self.scrollView.kx_width;
    
    // 取出子控制器
    UIViewController *childVc = self.childViewControllers[index];
    if ([childVc isViewLoaded]) return;
    
    childVc.view.frame =  self.scrollView.bounds ;
    [self.scrollView addSubview:childVc.view];
}

#pragma mark - <UIScrollViewDelegate>
/**
 * 在scrollView滚动动画结束时, 就会调用这个方法
 * 前提: 使用setContentOffset:animated:或者scrollRectVisible:animated:方法让scrollView产生滚动动画
 */
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [self addChildVcView];
}

/**
 * 在scrollView滚动动画结束时, 就会调用这个方法
 * 前提: 人为拖拽scrollView产生的滚动动画
 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 选中\点击对应的按钮
    NSUInteger index = scrollView.contentOffset.x / scrollView.kx_width;
    TKYTitleButton *titleButton = self.titlesView.subviews[index];
    [self titleClick:titleButton];
    
    // 添加子控制器的view
    [self addChildVcView];
    
    // 当index == 0时, viewWithTag:方法返回的就是self.titlesView
       // TKYTitleButton *titleButton = (TKYTitleButton *)[self.titlesView viewWithTag:index];
}

#pragma  mark-- TKYCustomChartsDelegate
- (void)TKY_customChartsDidSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    TKYQuestionTypeListModel *model = self.questionTypeListArr[indexPath.row];
    NSLog(@"%@",model.name);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"name" object:self.allSafetyVC.str];
    NSLog(@"%@",[NSString stringWithFormat:@"点击了那个%ld",indexPath.row]);
}


//- (TKYCustomCharts *)customCharts{
//    if (_customCharts == nil) {
//
//    }
//    return _customCharts;
//}

//显示时间的
- (TKYDateView *)dateView{
    if (_dateView == nil) {
        _dateView = [[TKYDateView alloc]initWithFrame:CGRectMake(0, MyNavBarHeight, kScreenWidth, kHeightScale *35)];
        __weak typeof(_dateView) weakDateView = self.dateView;
        __weak typeof(self) weakSelf = self;
        
        //开始时间
        self.projectInfoModel = [TKYProjectInfoModel sharedProjectInfoModel];
        _dateView.startDateView.dateLabel.text = self.projectInfoModel.startDateStr;
        _dateView.startDateView.selectedDateBtnBlock = ^(UIButton *btn) {
            [BRDatePickerView showDatePickerWithTitle:@"请选择开始日期" dateType:BRDatePickerModeYMD defaultSelValue:@"" resultBlock:^(NSString *selectValue) {
                weakDateView.startDateView.dateLabel.text = selectValue;
                [weakSelf requestQualityQuestionTypeAndCount:selectValue withEndDateStr:weakSelf.projectInfoModel.endDateStr];
            }];
        };
        
        //结束时间
        _dateView.endDateView.dateLabel.text = self.projectInfoModel.endDateStr;
        _dateView.endDateView.selectedDateBtnBlock = ^(UIButton *btn) {
            [BRDatePickerView showDatePickerWithTitle:@"请选择结束日期" dateType:BRDatePickerModeYMD defaultSelValue:@"" resultBlock:^(NSString *selectValue) {
                weakDateView.endDateView.dateLabel.text = selectValue;
                [weakSelf requestQualityQuestionTypeAndCount:weakSelf.projectInfoModel.startDateStr withEndDateStr:selectValue];
            }];
        };
    }
    return _dateView;
}

@end
